import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
import Mock from 'mockjs'
import { setupDashboardMock } from './dashboard'
import { setupUserMock } from './user'
import { setupEquipmentMock } from './equipment'
import { setupCommandMock } from './command'
import { setupCompanyMock } from './company'
import { setupAgreementMock } from './agreement'

// 创建mock适配器
const mock = new MockAdapter(axios, { 
  delayResponse: 500,
  onNoMatch: 'passthrough' // 未匹配到的请求将被传递给真实服务器
})

// 添加请求记录功能
const methods = ['get', 'post', 'put', 'delete']
const originalHandlers = {}

// 保存原始处理器
methods.forEach(method => {
  originalHandlers[method] = mock[`on${method.charAt(0).toUpperCase()}${method.slice(1)}`].bind(mock)
})

// 重写拦截器方法，添加日志但不影响原始功能
methods.forEach(method => {
  const methodName = `on${method.charAt(0).toUpperCase()}${method.slice(1)}`
  mock[methodName] = function(urlOrRegExp, ...args) {
    console.log(`注册${method.toUpperCase()}请求处理器:`, urlOrRegExp)
    return originalHandlers[method](urlOrRegExp, ...args)
  }
})

// 安装各模块的mock数据
export function setupMock() {
  console.log('开始安装mock服务...')
  
  setupDashboardMock(mock)
  setupUserMock(mock)
  setupEquipmentMock(mock)
  setupCommandMock(mock)
  setupCompanyMock(mock)
  setupAgreementMock(mock)
  
  console.log('所有mock服务已安装完成')
}

// 在开发环境下自动应用Mock
if (process.env.NODE_ENV !== 'production') {
  setupMock()
  console.log('Mock服务已启动')
}

// 设置全局mock配置
Mock.setup({
  timeout: '300-600'
})

console.log('Mock service started.') 